# coding: utf8
import json
import os
from wox import Wox, WoxAPI



#用户写的Python类必须继承Wox类 https://github.com/qianlifeng/Wox/blob/master/PythonHome/wox.py
#这里的Wox基类做了一些工作，简化了与Wox通信的步骤。
class Main(Wox):
    def __init__(self, *args, **kwargs):
        dotfiles_dir = os.getenv('DOTFILES')
        vip_path = os.path.join(dotfiles_dir, 'local', 'qq', 'important.json')
        print(vip_path)
        with open(vip_path, encoding='utf-8') as fp:
            self.data = json.loads(fp.read())
        return super(Main, self).__init__(*args, **kwargs)


    #必须有一个query方法，用户执行查询的时候会自动调用query方法
    def query(self, key):
        key = ' '.join(key.split(' ')[1:])
        def contruct_url(qq):
            url_scheme = "tencent://message/?uin={0}\u0026Site=qq\u0026Menu=yes"
            return url_scheme.format(qq)


        def key_in(key, items):
            for i in items:
                if key in i:
                    return True
            return False
        results = filter(lambda x: key_in(key, self.data[x]['keys']), self.data)
        showing = [{
            "Title": k,
            "SubTitle": self.data[k]['keys'],
            "JsonRPCAction":{
            # 这里除了自已定义的方法，还可以调用Wox的API。调用格式如下：Wox.xxxx方法名
            # 方法名字可以从这里查阅https://github.com/qianlifeng/Wox/blob/master/Wox.Plugin/IPublicAPI.cs 直接同名方法即可
            "method": "openUrl",
            "IcoPath":"Images/app.ico",
            #参数必须以数组的形式传过去
            "parameters":[contruct_url(self.data[k]['qq'])],
            # 是否隐藏窗口
            "dontHideAfterAction":True
            }
        } for k in results]
        showing.append({
            "Title": "Nothing",
            "SubTitle": "something",
        })
        # print(showing)
        return showing


    def openUrl(self,url):
        webbrowser.open(url)
        WoxAPI.change_query(url)


if __name__ == "__main__":
    Main()
    # Main().query('z')
